package view.collection.trie;

import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.KeyEvent;

import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

import view.common.JTextFieldLimit;
import controller.TrieController;
import dataStructure.DataStructureApplet;

/**
 * Representa al panel que contiene los botones de operaciones para el Trie.
 * 
 * 
 */
public class TrieButtonsPanel extends JPanel {
	private static final long serialVersionUID = 1202333466570609044L;
	private static final int MAX_INPUT_LENGTH = 15;

	private TrieController controller;

	/** Creates new form Panel */
	public TrieButtonsPanel() {
		this.controller = null;
		initComponents();
	}

	/**
	 * Agrega un controlador
	 * 
	 * @param controller
	 *            controlador a agregar
	 */
	public void addController(TrieController controller) {
		this.controller = controller;
	}

	/**
	 * Habilita o desactiva los elementos del panel.
	 * 
	 * @param b
	 *            true si el los elementos deben habilitarse, false en caso
	 *            contrario.
	 */
	public void setEnabledButtons(boolean b) {
		this.insertButton.setEnabled(b);
		this.removeButton.setEnabled(b && !controller.isTrieEmpty());
		this.demoButton.setEnabled(b);
		this.clearButton.setEnabled(b && !controller.isTrieEmpty());
		this.textField.setEnabled(b);
	}

	/**
	 * Determina si los elementos del panel estan habilitados (o no)
	 * 
	 * @return true si estan habilitados, false en caso contrario.
	 */
	public boolean isEnabledButtons() {
		return this.insertButton.isEnabled();
	}

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	// <editor-fold defaultstate="collapsed" desc="Generated
	// <editor-fold defaultstate="collapsed"
	// desc="Generated Code">//GEN-BEGIN:initComponents
	private void initComponents() {
		// setBackground(new java.awt.Color(255, 255, 255));
		setBorder(BorderFactory.createTitledBorder("Control: Trie"));
		setLayout(new FlowLayout(java.awt.FlowLayout.LEFT));

		jLabel1 = new JLabel("Ingresá hasta " + MAX_INPUT_LENGTH
				+ " caracteres");
		jLabel1.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 14));

		textField = new JTextField();
		textField.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 16));
		textField.setDocument(new JTextFieldLimit(MAX_INPUT_LENGTH));
		textField.setColumns(MAX_INPUT_LENGTH);
		textField.putClientProperty("JComponent.sizeVariant", "large");
		textField.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				textFieldActionPerformed(evt);
			}
		});
		add(jLabel1);
		add(textField);

		jPanel1 = new JPanel();
		jPanel1.setLayout(new java.awt.GridLayout(1, 0));
		add(jPanel1);

		Icon addIcon = new ImageIcon(DataStructureApplet.BUTTON_ADD_IMAGE);
		insertButton = new JButton("Insertar", addIcon);
		insertButton.setVerticalTextPosition(SwingConstants.BOTTOM);
		insertButton.setHorizontalTextPosition(SwingConstants.CENTER);
		insertButton.putClientProperty("JComponent.sizeVariant", "small");
		insertButton.setToolTipText("Insertar elemento en el árbol");
		insertButton.setMargin(new java.awt.Insets(2, 5, 2, 5));
		insertButton.setMnemonic(KeyEvent.VK_I);
		insertButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				insertButtonActionPerformed(evt);
			}
		});
		add(insertButton);

		Icon deleteIcon = new ImageIcon(DataStructureApplet.BUTTON_DELETE_IMAGE);
		removeButton = new JButton("Eliminar", deleteIcon);
		removeButton.setVerticalTextPosition(SwingConstants.BOTTOM);
		removeButton.setHorizontalTextPosition(SwingConstants.CENTER);
		removeButton.putClientProperty("JComponent.sizeVariant", "small");
		removeButton.setToolTipText("Eliminar elemento del árbol");
		removeButton.setMargin(new java.awt.Insets(2, 5, 2, 5));
		removeButton.setMnemonic(KeyEvent.VK_E);
		removeButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				removeButtonActionPerformed(evt);
			}
		});
		add(removeButton);

		Icon randomIcon = new ImageIcon(DataStructureApplet.BUTTON_RANDOM_IMAGE);
		demoButton = new JButton("Random", randomIcon);
		demoButton.setVerticalTextPosition(SwingConstants.BOTTOM);
		demoButton.setHorizontalTextPosition(SwingConstants.CENTER);
		demoButton.putClientProperty("JComponent.sizeVariant", "small");
		demoButton.setToolTipText("Insertar elemento aleatorio");
		demoButton.setMargin(new java.awt.Insets(2, 5, 2, 5));
		demoButton.setMnemonic(KeyEvent.VK_R);
		demoButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				demoButtonActionPerformed(evt);
			}
		});
		add(demoButton);

		Icon cleanIcon = new ImageIcon(DataStructureApplet.BUTTON_REFRESH_IMAGE);
		;
		clearButton = new JButton("Vaciar", cleanIcon);
		clearButton.setVerticalTextPosition(SwingConstants.BOTTOM);
		clearButton.setHorizontalTextPosition(SwingConstants.CENTER);
		clearButton.putClientProperty("JComponent.sizeVariant", "small");
		clearButton.setToolTipText("Vaciar árbol");
		clearButton.setMargin(new java.awt.Insets(2, 5, 2, 5));
		clearButton.setMnemonic(KeyEvent.VK_V);
		clearButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				clearButtonActionPerformed(evt);
			}
		});
		add(clearButton);
	}// </editor-fold>//GEN-END:initComponents

	private void demoButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_demoButtonActionPerformed
		controller.generateWords();
	}// GEN-LAST:event_demoButtonActionPerformed

	private void clearButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_clearButtonActionPerformed
		int res = JOptionPane.OK_OPTION;
		if (!controller.isTrieEmpty()) {
			res = JOptionPane.showConfirmDialog(null,
					"Se eliminarán todos los elementos.\n¿Continuar?",
					"Vaciar", JOptionPane.YES_NO_OPTION);
		}

		if (res == JOptionPane.OK_OPTION) {
			controller.clear();
		}

	}// GEN-LAST:event_clearButtonActionPerformed

	private void insertButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_insertButtonActionPerformed
		String text = getText();
		try {
			if (text == null || text.isEmpty()) {
				controller
						.showLogMessage("ERROR: El valor ingresado no debe ser vacío.");
			} else if (!text.matches("[A-Za-z0-9]*")) {
				controller
						.showLogMessage("ERROR: El texto ingresado debe contener sólo carácteres alfanuméricos.");
			} else {
				controller.insertWord(text.toLowerCase());
			}
		} finally {
			textField.setText("");
		}
	}// GEN-LAST:event_insertButtonActionPerformed

	private void textFieldActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_textFieldActionPerformed

		this.insertButtonActionPerformed(evt);
	}// GEN-LAST:event_textFieldActionPerformed

	private void removeButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_removeButtonActionPerformed
		String text = getText();
		try {
			if (text == null || text.isEmpty()) {
				controller
						.showLogMessage("ERROR: El valor ingresado no debe ser vacío.");
			} else if (!text.matches("[A-Za-z0-9]*")) {
				controller
						.showLogMessage("ERROR: El texto ingresado debe contener sólo caracteres alfanuméricos.");
			} else {
				controller.removeWord(text.toLowerCase());
			}
		} finally {
			textField.setText("");
		}
	}// GEN-LAST:event_removeButtonActionPerformed

	private String getText() {
		String text = textField.getText();
		textField.grabFocus();
		textField.selectAll();
		return text;
	}

	// Variables declaration - do not modify//GEN-BEGIN:variables
	private JButton clearButton;
	private JButton demoButton;
	private JButton insertButton;
	private JPanel jPanel1;
	private JButton removeButton;
	private JTextField textField;
	private JLabel jLabel1;
	// End of variables declaration//GEN-END:variables
}
